import os
import sys
import cv2
import numpy as np
import struct
import binascii

def process_video(input_video, target_width, target_height):
    """将输入视频处理为合适的分辨率"""
    cap = cv2.VideoCapture(input_video)
    frame_count = 0
    processed_frames = []

    while cap.isOpened():
        ret, frame = cap.read()
        if not ret:
            break

        # 将视频帧调整到目标分辨率
        resized_frame = cv2.resize(frame, (target_width, target_height))
        processed_frames.append(resized_frame)
        frame_count += 1

    cap.release()
    print(f"视频处理完成，总帧数：{frame_count}")
    return processed_frames

def extract_frame_data(frame):
    """从视频帧中提取二进制数据（模拟数据提取过程）"""
    binary_data = np.random.bytes(1491)  # 每帧1491字节模拟数据
    return binary_data

def combine_frames_into_bin(frames, bin_file):
    """将30帧数据合并到一个二进制文件中"""
    with open(bin_file, 'wb') as f:
        for frame in frames:
            f.write(frame)
    print(f"生成二进制文件: {bin_file}")

def compare_and_generate_val_files(decoded_file, original_file, val_file):
    """生成 .val 文件，比较解码后的二进制文件和原始文件"""
    with open(decoded_file, 'rb') as df, open(original_file, 'rb') as of, open(val_file, 'wb') as vf:
        decoded_content = df.read()
        original_content = of.read()

        # 逐字节比较生成 .val 文件，1表示正确，0表示错误
        val_content = bytearray(len(original_content))
        for j in range(len(original_content)):
            val_content[j] = 1 if j < len(decoded_content) and decoded_content[j] == original_content[j] else 0

        vf.write(val_content)
    print(f"{val_file} 文件生成完成")

def decode_video_to_bin_files(frames, output_dir):
    """每30帧合并生成一个二进制文件"""
    decoded_files = []
    frames_per_bin = 30  # 每个bin文件对应30帧

    for i in range(0, len(frames), frames_per_bin):
        bin_frames = [extract_frame_data(frame) for frame in frames[i:i + frames_per_bin]]

        # 合并30帧数据并保存为 .bin 文件
        file_name = os.path.join(output_dir, f"{(i // frames_per_bin) + 1}.bin")
        combine_frames_into_bin(bin_frames, file_name)
        decoded_files.append(file_name)

    return decoded_files

def main():
    if len(sys.argv) != 3:
        print("用法: python decode.py <视频文件> <输出目录>")
        sys.exit(1)

    input_video = sys.argv[1]  # 输入视频文件
    output_dir = sys.argv[2]   # 输出目录

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 设定处理后的分辨率（和编码时保持一致）
    target_width, target_height = 320, 240

    # 处理输入视频，将其转换为合适的分辨率
    frames = process_video(input_video, target_width, target_height)

    # 解码视频帧为二进制文件，每30帧合并为一个 .bin 文件
    decoded_files = decode_video_to_bin_files(frames, output_dir)

    # 原始文件保存在与当前同目录的 `./` 目录下
    original_dir = './'
    original_files = [os.path.join(original_dir, f"{i}.bin") for i in range(1, 4)]

    # 比较解码的文件与原始文件，生成 .val 文件
    for i, decoded_file in enumerate(decoded_files):
        original_file = original_files[i]
        val_file = os.path.join(output_dir, f"{i + 1}.val")
        compare_and_generate_val_files(decoded_file, original_file, val_file)

if __name__ == "__main__":
    main()
